package com.example.demo.service;

import com.example.demo.repository.*;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.*;
import com.example.demo.model.*;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.Set;

@Service
public class BlogPostService {
    @Autowired
    private BlogPostRepository blogPostRepository;

    @Autowired
    private AuthorRepository authorRepository;

    @Transactional
    public BlogPost saveBlogPostWithAuthor(BlogPost blogPost) {
        Author author = blogPost.getAuthor();
        if (null != author) {

            Author currentAuthor = authorRepository.findById(blogPost.getAuthor().getId()).orElse(null);
            if (null != currentAuthor) {
                currentAuthor.setName(blogPost.getAuthor().getName());
                blogPost.setAuthor(currentAuthor);
            } else {
                authorRepository.save(author);
            }

        }
        return blogPostRepository.save(blogPost);
    }

    public Optional<BlogPost> getBlogPostById(Long id) {
        return blogPostRepository.findById(id);
    }


    public BlogPost saveBlogPost(BlogPost blogPost) {

        return blogPostRepository.save(blogPost);
    }

//    public Set<BlogPost> getBlogPostsByAuthor(Author author) {
//        return blogPostRepository.findByAuthor(author);
//    }
}
